import Plugin from '../plugin'
import {EN,CN} from '../../config'
import Utils from '../../utils'
const cssText = `
.#{icn.root}{
    padding: 0;
    border: 1px solid #969696;
    border-top:none;
    background-color:#fff;
    box-sizing: border-box;
}
.#{icn.root} .#{icn.item}{
	text-indent: 10px;
	transition:all 0.3s linear;
	display: flex;
    justify-content: space-between;
}
.#{icn.root} .#{icn.item} .#{cn.iconfont}{
	margin-right:10px;
}
`
const itemTpl = `
<li class="#{data.item} #{data.action}" 
	data-dtype="#{data.li.dtype}"
	data-title="#{data.li.title}"
	data-arg="#{data.li.arg}">
<span>#{data.li.title}</span><span class="${CN.iconfont} #{data.li.icon}"></span>
</li>
`
export default class DataList extends Plugin{
	constructor(...args){
		super(...args)
		this.name="DataList"
		this.createClassName({
			root:"data-list",
			item:"data-list-option"
		})
		this.injectStyle(cssText,this.cn)
		this.render()
		this.bind()
	}
	bind(){
		this.$layer.addEventListener("click",(e)=>{
			this.focusOut()
		})
		this.$picker.addEventListener("click",(e)=>{
			e.stopPropagation()
			this.onPick(e)
		})
	}
	render(){
		this.createLayer(CN.hide)
		this.$picker = document.createDOM("ul",{
			class:[this.cn.root,CN.abs].join(" ")
		})
		this.$layer.appendChild(this.$picker)
	}
	onPick(e){
		let target = e.target
		target = target.classList.contains(this.cn.item)?target:target.parentNode
		this.target.value = target.dataset.title
		var evt = document.createEvent('HTMLEvents')
			evt.initEvent('change', true, true)
		this.target.dispatchEvent(evt)
		this.focusOut()
		this.emit(EN.onPick,e.target.dataset.arg)
	}
	renderItems(list){
		this.$picker.innerHTML = list.map(li=>{
			return Utils.parseText(itemTpl,this.cn.assign({li,action:CN.action}))
		}).join("")
	}
	focusIn(data){
		let {target} = data
		let {x,y,width,height} = target.getBoundingClientRect()
		this.target = target
		this.renderItems(Utils.dataTransform(target.nextElementSibling.innerHTML,"object"))
		this.$picker.style.cssText = `left:${x}px;top:${y+height}px;width:${width}px`
		this.$layer.classList.remove(CN.hide)
	}
	focusOut(){
		this.target = null
		this.$layer.classList.add(CN.hide)
	}
}